package com.example.demo.controller;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Admin;
import com.example.demo.entity.User;
import com.example.demo.mapper.AdminMapper;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController//用来访问json数据
@RequestMapping("/admin")//定义统一路由
public class AdminController {
    @Resource
    AdminMapper adminMapper;

    @PostMapping("/login")//登录逻辑
    public Result<?> login(@RequestBody Admin admin){
        //获取匹配的密码和用户名，如果不匹配则输出错误信息
        Admin res = adminMapper.selectOne(Wrappers.<Admin>lambdaQuery().eq(Admin::getUsername, admin.getUsername()).eq(Admin::getPassword, admin.getPassword()));
//        System.out.println(user.getUsername());
//        System.out.println( user.getPassword());
        if(res == null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }


    @PostMapping//post新增
    public Result<?> save(@RequestBody Admin admin){
        if(admin.getPassword() == null){
            admin.setPassword("123456");
        }
        //insert已经封装好了不用知道细节
        adminMapper.insert(admin);
        return Result.success();
    }
    @DeleteMapping("/{id}")//删除
    public Result<?> save(@PathVariable Long id){

        adminMapper.deleteById(id);
        return Result.success();
    }

    @PutMapping//更新
    public Result<?> update(@RequestBody Admin admin){


        adminMapper.updateById(admin);
        return Result.success();
    }
    @GetMapping//查询
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,//defaultValue设置默认页数
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Admin> wrapper = Wrappers.<Admin>lambdaQuery().like(Admin::getName, search);

        if(StrUtil.isNotBlank(search)){
            wrapper.like(Admin::getName,search);
        }
        Page<Admin> adminPage = adminMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(adminPage);
    }
}
